package com.ruoyi.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.minio.server.MinioService;
import com.ruoyi.entity.VerActivityGroup;
import com.ruoyi.product.domain.ProductActivity;
import com.ruoyi.service.VerActivityGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/activity_group")
public class VerActivityGroupController extends BaseController {

    @Autowired
    private VerActivityGroupService verActivityGroupService;
    @Autowired
    private MinioService minioService;

    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 查询活动组列表
     */
    @GetMapping("/list")
    public TableDataInfo list(VerActivityGroup verActivityGroup)
    {
        startPage();
        List<VerActivityGroup> list = verActivityGroupService.selectVerActivityGroupList(verActivityGroup);
        return getDataTable(list);
    }

    /**
     * 根据活动组ID获取活动列表
     */
    @GetMapping("/groupList/{groupId}")
    public AjaxResult getActivitiesByGroupId(@PathVariable Long groupId) {
        try {
            List<ProductActivity> activities = verActivityGroupService.getActivitiesByGroupId(groupId);
            return AjaxResult.success(activities);
        } catch (Exception e) {
            return AjaxResult.error("获取活动组详情失败：" + e.getMessage());
        }
    }

    /**
     * 获取活动组详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(verActivityGroupService.selectVerActivityGroupById(id));
    }

    /**
     * 新增活动组
     */
    @Log(title = "活动组", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult add(@RequestParam("activityGroup") String activityGroupJson,
                          @RequestParam(value = "file", required = false) MultipartFile file) {
        try {
            // 手动解析 JSON 字符串为对象
            VerActivityGroup verActivityGroup = objectMapper.readValue(activityGroupJson, VerActivityGroup.class);

            // 保存活动组信息
            boolean success = verActivityGroupService.insertVerActivityGroup(verActivityGroup);
            if (!success) {
                return AjaxResult.error("活动组保存失败");
            }

            // 如果上传了文件，则处理图片上传
            if (file != null && !file.isEmpty()) {
                // 生成文件名
                String originalFileName = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFileName != null && originalFileName.contains(".")) {
                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                String fileName = "activity_group_" + verActivityGroup.getId() + "_" + System.currentTimeMillis() + fileExtension;

                // 上传文件到MinIO
                Map<String, String> uploadResult = minioService.uploadFile(file, fileName);

                if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                    // 更新活动组的图片URL
                    verActivityGroup.setUrl(uploadResult.get("fileUrl"));
                    verActivityGroupService.updateVerActivityGroup(verActivityGroup);
                } else {
                    return AjaxResult.error("图片上传失败");
                }
            }
            return AjaxResult.success("活动组新增成功");
        } catch (Exception e) {
            return AjaxResult.error("新增活动组失败：" + e.getMessage());
        }
    }

    /**
     * 修改活动组
     */
    @Log(title = "活动组", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult edit(@RequestParam("activityGroup") String activityGroupJson,
                           @RequestParam(value = "file", required = false) MultipartFile file) {
        try {
            // 手动解析 JSON 字符串为对象
            VerActivityGroup verActivityGroup = objectMapper.readValue(activityGroupJson, VerActivityGroup.class);

            // 如果上传了新图片，则先上传到MinIO
            if (file != null && !file.isEmpty()) {
                // 生成文件名
                String originalFileName = file.getOriginalFilename();
                String fileExtension = "";
                if (originalFileName != null && originalFileName.contains(".")) {
                    fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                }
                String fileName = "activity_group_" + verActivityGroup.getId() + "_" + System.currentTimeMillis() + fileExtension;

                // 上传文件到MinIO
                Map<String, String> uploadResult = minioService.uploadFile(file, fileName);

                if (uploadResult != null && "true".equals(uploadResult.get("success"))) {
                    // 设置新的图片URL
                    verActivityGroup.setUrl(uploadResult.get("fileUrl"));
                } else {
                    return AjaxResult.error("图片上传失败");
                }
            }
            // 更新活动组信息
            return toAjax(verActivityGroupService.updateVerActivityGroup(verActivityGroup));
        } catch (Exception e) {
            return AjaxResult.error("修改活动组失败：" + e.getMessage());
        }
    }

    /**
     * 删除活动组
     */
    @Log(title = "活动组", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(verActivityGroupService.deleteVerActivityGroupByIds(ids));
    }

}
